'use strict'

const playerHandle = require('../core/playerHandle')
const route = require('../module/route')
const playerSessionMgr = require('../core/playerSessionMgr')

let playerLogin = function(uId, msg, next) {
    let pId = msg.pId
    let query = {
        uId: uId,
        _id: pId
    }
    playerHandle.getPlayer(query, function(err, res) {
        if (err) {
            next(101)
            return
        }
        if (res === null) {
            next(1)
            return
        }
        let player = playerHandle.initPlayer(res)
        playerSessionMgr.bind(player)
        next(0, player)
    })
}

//角色登陆
route.setNotLogin('playerLogin', playerLogin, {1: '角色不存在'})

route.set('playerLogin', function(player, msg, next) {
    let pId = msg.pId
    let query = {
        uId: player.uId,
        _id: pId
    }
    playerHandle.getPlayer(query, function(err, res) {
        if (err) {
            next(101)
            return
        }
        if (res === null) {
            next(1)
            return
        }
        let player = playerHandle.initPlayer(res)
        player.loginTime = new Date().getTime()
        playerSessionMgr.bind(player)
        next(0, player)
    })
}, {1: '角色不存在'})

//获取角色列表
route.setNotLogin('getPlayerList', function(uId, msg, next) {
    playerHandle.getPlayers(uId, function(err, res) {
        if (err) {
            next(101)
            return
        }
        next(0, res)
    })
}, {1: '角色不存在'})

//获取角色列表
route.set('getPlayerList', function(player, msg, next) {
    playerHandle.getPlayers(player.uId, function(err, res) {
        if (err) {
            next(101)
            return
        }
        next(0, res)
    })
}, {1: '角色不存在'})

//创建角色
route.setNotLogin('createPlayer', function(uId, msg, next) {
    let name = msg.name
    let query = {
        'player.basicInfo.name': name
    }
    playerHandle.getPlayer(query, function(err, res) {
        if (err) {
            next(101)
            return
        }
        if (res) {
            next(1)
            return
        }
        playerHandle.create(uId, name, function(player) {
            next(0)
        })
    })
}, {1: '角色名已经存在'})

//获取名称列表
route.set('getPropName', function(player, msg, next) {
    next(0, SUN.propName)
})

//获取配置
route.set('getTotalConfig', function(player, msg, next) {
    next(0, SUN.totalConfig)
})
